<template>
  <page-header-wrapper>
    <a-card>
      <a-divider>发布通知</a-divider>
      
      <a-form :form='form' :label-col='{ span: 6 }' :wrapper-col='{ span: 12 }' @submit='handleSubmit'>
        
        <a-form-item label='标题' :label-col='{ span: 9 }' :wrapper-col='{ span: 7 }'>
          <a-input
            placeholder='请输入标题'
            v-decorator="['title', { rules: [{ required: true, message: '标题不能为空' }] }]"
          />
        </a-form-item>
        
        <a-form-item label='显示时长' :label-col='{ span: 9 }' :wrapper-col='{ span: 7 }'>
          <a-input-number
            :min='-1' :max='20'
            style='width: 100%;'
            placeholder='请输入显示时长(单位: 秒) 输入-1为永不过期'
            v-decorator="['duration', { rules: [{ required: true, message: '显示时长不能为空' }] }]"
          />
        </a-form-item>
        
        <a-form-item label='窗口宽度' :label-col='{ span: 9 }' :wrapper-col='{ span: 7 }'>
          <a-input-number
            :min='500' :max='1500'
            style='width: 100%;'
            placeholder='请输入窗口宽度(单位px)'
            v-decorator="['width', {initialValue: 500}, { rules: [{ required: true, message: '窗口宽度不能为空' }] }]"
          />
        </a-form-item>
        
        <a-form-item label='程度' :label-col='{ span: 9 }' :wrapper-col='{ span: 7 }'>
          <a-select
            v-decorator="['level',{ rules: [{ required: true, message: '通知程度不能为空' }] },]"
            placeholder='请选择此次通知的重要程度'
          >
            <a-select-option value='0'>
              📢信息
            </a-select-option>
            <a-select-option value='1'>
              🚧警告
            </a-select-option>
            <a-select-option value='2'>
              ❌错误
            </a-select-option>
          </a-select>
        </a-form-item>
        
        <a-tooltip>
          <template slot='title'>
            HTML格式 支持样式,链接,图片,动画
          </template>
          <a-form-item label='通知内容(HTML格式)' :label-col='{ span: 6 }'>
            
            <BaseIDE code-mode='htmlmixed'
                     :ide-font-size='18'
                     style='font-weight: 580;'
                     :ide-height="'200px'"
                     v-decorator="['htmlContent', { rules: [{ required: true, message: '通知内容不能为空或为模板内容' }] }]"
                     codeTemplate="<h3 style='color:red'>消息内容</h3>
第十题出现错误 请将 [a = 1] 改成 [ a = 2 ]
<img src=&quot;https://i0.hdslb.com/bfs/archive/d47983e20a3f7125b4859fa72f648c4a3370716f.png&quot;>
"
                     @getCodeAnswer='getNotice' />
          </a-form-item>
        
        </a-tooltip>
        
        <a-row type='flex' justify='end'>
          
          <a-tooltip>
            <template slot='title'>
              演示模式供调试使用 仅自己可见
            </template>
            <a-button
              type='dashed'
              @click='handleSubmit'>演示
            </a-button>
          </a-tooltip>
          
          <a-tooltip>
            <template slot='title'>
              在线图床 上传图片和获取图片在线访问的地址 有效期30天
            </template>
            <a-button
              style='margin-left: 15px;'
              @click='visibleDrawingBed = true'
              type='dashed'>
              在线图床
            </a-button>
          </a-tooltip>
          
          <a-button
            style='margin-left: 15px;margin-right: 15px;'
            @click='() => this.form.resetFields()'>
            重置
          </a-button>
          
          <a-col :span='8'>
            <a-popconfirm
              ok-text='确认'
              placement='right'
              cancel-text='取消'
              @confirm='confirm'
              @cancel='cancel'
            >
              <template slot='title'>
                <p>确认发布此次消息?</p>
                <p>一经发布不能修改不能撤回</p>
              </template>
              <a-button
                type='primary'>
                发布
              </a-button>
            </a-popconfirm>
          </a-col>
        
        
        </a-row>
      
      </a-form>
    
    </a-card>
    
    <a-card style='margin-top: 50px;'>
      
      <!--搜索区域-->
      <div class='table-page-search-wrapper'>
        <a-form layout='inline'>
          <a-row :gutter='48'>
            <a-col :md='8' :sm='24'>
              <a-form-item label='操作名称'>
                <a-input v-model='queryParam.title' placeholder='请输入操作名称或关键字' />
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='创建人'>
                <a-input v-model='queryParam.createBy' placeholder='请输入创建人姓名' />
              </a-form-item>
            </a-col>
            <a-button type='primary' @click='getNoticeHistoryList'>查询</a-button>
            <a-button style='margin-left: 8px' @click='() => this.queryParam = {}'>重置</a-button>
          </a-row>
        </a-form>
      </div>
      
      <a-divider orientation='right'><h3>历史通知</h3></a-divider>
      <a-table
        :columns='columns'
        rowKey='noticeId'
        :pagination='pagination'
        bordered
        :loading='loading'
        @change='handleTableChange'
        :data-source='tableData'>
        
        <template slot='htmlContent' slot-scope='htmlContent'>
          <a-popover title='HTML内容预览'>
            <template slot='content'>
              <div v-html='htmlContent'></div>
            </template>
            {{ htmlContent }}
          </a-popover>
        </template>
        
        <template slot='action' slot-scope='text, record, index'>
          
          <a-popconfirm
            title='确认删除次通知'
            ok-text='确认'
            cancel-text='取消'
            @confirm='del(record)'
          >
            <a-button
              type='error'
              style='border-radius: 5px'>删除
            </a-button>
          </a-popconfirm>
        </template>
      
      </a-table>
    </a-card>
    
    <!--图片上传-->
    <a-modal
      title='在线图床'
      :visible='visibleDrawingBed'
      :confirm-loading='confirmLoading'
      @ok='visibleDrawingBed = false'
      okText='确认'
      cancelText='取消'
      :maskClosable='false'
      @cancel='visibleDrawingBed = false'>
      <a-upload
        name='file'
        :multiple='true'
        :customRequest='customUpload'>
        <a-button>
          <a-icon type='upload' />
          上传图片
        </a-button>
      </a-upload>
      
      <a-tooltip v-if='imageUrl'>
        <template slot='title'>
          点击图片复制URL
        </template>
        <img v-if='imageUrl'
             :src='imageUrl'
             alt='点击复制图片URL'
             @click='copy(imageUrl)'
             style='width: 50%;margin-top: 20px;text-align: center;' />
      </a-tooltip>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import BaseIDE from '@/views/reply/components/BaseIDE.vue'
import { delNoticeById, getNoticeHistoryList, setNotice } from '@/api/notice'
import { drawingBedUploadImg } from '@/api/common'

const columns = [
  {
    title: '通知编号',
    dataIndex: 'noticeId',
    width: 100,
    scopedSlots: { customRender: 'noticeId' }
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 150,
    scopedSlots: { customRender: 'title' }
  },
  {
    title: '内容',
    dataIndex: 'htmlContent',
    scopedSlots: { customRender: 'htmlContent' }
  },
  {
    title: '创建人',
    dataIndex: 'createBy',
    width: 130,
    scopedSlots: { customRender: 'createBy' }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
    scopedSlots: { customRender: 'createTime' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    width: 50,
    fixed: 'right'
  }
]

export default {
  components: {
    BaseIDE
  },
  name: 'Notice',
  data() {
    return {
      htmlContent: '',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      columns,
      formLayout: 'horizontal',
      // 图床弹出框
      visibleDrawingBed: false,
      // 图片上传
      confirmLoading: false,
      imageUrl: '',
      // 加载动画
      loading: true,
      // 数据
      tableData: [],
      // 查询参数
      queryParam: {},
      // 分页参数
      pagination: {
        size: 'large',
        current: 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: ['10', '15', '20'],//可选的页面显示条数
        showTotal: (total, range) => {
          return ' 共' + total + '条'
        }, //展示每页第几条至第几条和总数
        hideOnSinglePage: false, // 只有一页时是否隐藏分页器
        showQuickJumper: true, //是否可以快速跳转至某页
        showSizeChanger: true //是否可以改变pageSize
      }
      
    }
  },
  created() {
    this.getNoticeHistoryList()
  },
  methods: {
    getNotice(msg) {
      // 实时赋值
      this.form.setFieldsValue({ 'htmlContent': msg })
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('表单内容为', values)
          this.openNotification(values.title, values.duration, values.width, values.level, values.htmlContent)
        }
      })
    },
    // 确认发布
    confirm(e) {
      // 发送请求
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          setNotice(values).then(response => {
            this.$message.success('发布成功')
            this.getNoticeHistoryList()
          })
        }
      })
    },
    // 取消发布
    cancel(e) {
      this.$message.error('取消发布')
    },
    // 消息通知
    openNotification(title, duration = 5, width = 640, level, htmlContent) {
      let icon = null
      if (duration === -1) {
        duration = null
      }
      
      if (level === '0') {
        icon = <a-icon type='info-circle' theme='twoTone' />
      } else if (level === '1') {
        icon = <a-icon type='stop' theme='twoTone' />
      } else {
        icon = <a-icon type='warning' theme='filled' style='color: #ff0000' />
      }
      const key = `open${Date.now()}`
      this.$notification.open({
        duration,
        message: title,
        style: {
          width: width + 'px',
          marginLeft: `${335 - width}px`
        },
        icon: icon,
        description: h('div', null, [
          h('p', { domProps: { innerHTML: htmlContent } }, null)
        ]),
        btn: h => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small'
              },
              on: {
                click: () => this.$notification.close(key)
              }
            },
            '确认'
          )
        },
        key,
        onClose: () => {
          console.log('确认')
        }
      })
    },
    customUpload(e) {
      drawingBedUploadImg({
        file: e.file
      }).then(response => {
        this.imageUrl = response.data.imgUrl
        e.onSuccess(response.data, e)
        this.$message.success('上传成功')
      }).catch((err) => {
        // 调用实例的失败方法通知组件该文件上传失败
        e.onError(err);
      });
    },
    // 获取历史消息
    getNoticeHistoryList() {
      this.loading = true
      getNoticeHistoryList(this.queryParam).then(response => {
        this.tableData = response.rows
        this.pagination.total = response.total
      })
      this.loading = false
    },
    del(record) {
      delNoticeById(record.noticeId).then(response => {
        this.$message.success('删除成功')
        this.getNoticeHistoryList()
      })
    },
    //表格改变时触发
    handleTableChange(pagination, filters, sorter) {
      this.pagination = pagination
      // 添加分页参数
      this.queryParam.pageNum = pagination.current
      this.queryParam.pageSize = pagination.pageSize
      
      this.getNoticeHistoryList()
    },
    copy(copyResult) {
      //创建input标签
      var input = document.createElement('input')
      //将input的值设置为需要复制的内容
      input.value = copyResult
      //添加input标签
      document.body.appendChild(input)
      //选中input标签
      input.select()
      //执行复制
      document.execCommand('copy')
      //成功提示信息
      this.$message.success('复制成功')
      //移除input标签
      document.body.removeChild(input)
    }
  }
}
</script>

<style scoped>

</style>